package com.drinks.yiniang.ui.widget.textview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import static android.graphics.Paint.ANTI_ALIAS_FLAG;

/**
 * @author han
 * @date 2020/1/15
 */
public class PayPasswordView extends AppCompatTextView {
    //当前输入总长度
    private int textLength;
    //密码总长度
    private int passwordLength = 6;
    //线宽
    private int borderWidth = 4;
    private int passwordWidth = 16;
    private int bolderColor = 0xFFA4A4A5;
    private Paint paint = new Paint(ANTI_ALIAS_FLAG);
    private Paint passwordPaint = new Paint(ANTI_ALIAS_FLAG);

    private OnPasswordInputCompleteListener onCompleteListener;

    public PayPasswordView(Context context) {
        this(context,null);
    }

    public PayPasswordView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public PayPasswordView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();

        //画分割线
        paint.setColor(bolderColor);
        paint.setStyle(Paint.Style.FILL);

        for (int i = 1; i < passwordLength; i++) {
            int startX = width / passwordLength * i;
            canvas.drawLine(startX, borderWidth, startX, height - borderWidth, paint);
        }

        // 密码
        passwordPaint.setStrokeWidth(passwordWidth);
        passwordPaint.setStyle(Paint.Style.FILL);
        passwordPaint.setColor(0xFF000000);

        float cx, cy = height / 2;
        float half = width / passwordLength / 2;
        for (int i = 0; i < textLength; i++) {
            cx = width * i / passwordLength + half;
            canvas.drawCircle(cx, cy, passwordWidth, passwordPaint);
        }

        if (this.textLength == 6 && onCompleteListener != null) {
            onCompleteListener.onComplete();
        }
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        this.textLength = text.toString().length();
        invalidate();
    }

    public void setOnPasswordCompleteLinstener(OnPasswordInputCompleteListener onCompleteListener) {
        this.onCompleteListener = onCompleteListener;
    }

    public interface OnPasswordInputCompleteListener {
        void onComplete();
    }
}
